<?php


namespace App\Http\observer;


use App\Models\CustomHouse;
use App\Models\House;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class HouseObserver
{
    public function saved(House $house)
    {

        DB::beginTransaction();
        try {
            $model=new CustomHouse();
            $model->where("house_id",$house->id)->delete();
            foreach ($house->customs as $k=>$v){
                $create=[
                    "cid"=>$v,
                    "house_id"=>$house->id
                ];
                $model->create($create);
            }
            $up=Cache::get("house_price_".$house->id);
           /* if ($up){
                Cache::forget("house_price_".$house->id);
                $update=["price_state",1];
            }else{
                $update=["price_state",0];
            }
            House::where("id",$house->id)->update($update);*/
            DB::commit();
        }catch (\Exception $exception)
        {
            Log::error($exception->getMessage());
            DB::rollBack();
            $house->delete();
        }
    }

    public function updating(House $house)
    {
       $ohouse=House::where("id",$house->id)->first();
       if($ohouse["price"]>$house->price){
           Cache::put("house_price_".$house->id,"up");
       }
    }

    public function deleted(House $house)
    {
        CustomHouse::where("house_id",$house->id)->delete();
    }
}
